package com.admin.education.common.jwt;

import com.admin.education.common.response.IResponseMessage;
import com.admin.education.common.exceptions.UnauthorizedException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureException;

import javax.servlet.http.HttpServletRequest;

public class JwtUtils {
    public static Object getClaims(HttpServletRequest request, String claim) throws UnauthorizedException {
        final String authHeader = request.getHeader("authorization");
        IResponseMessage responseMessage = null;
        String accept = request.getHeader("Accept");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            throw new UnauthorizedException("认证失败");
        }

        final String token = authHeader.substring(7);

        try {
            final Claims claims = Jwts.parser().setSigningKey("secretkey").parseClaimsJws(token).getBody();
            return claims.get(claim);
        } catch (final SignatureException e) {
            throw new UnauthorizedException("认证失败");
        }
    }
}
